package io.jpress.addon.partnershipauthorities.service.provider;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import io.jboot.aop.annotation.Bean;
import io.jpress.addon.partnershipauthorities.service.JpressAddonPartnershipauthoritiesService;
import io.jpress.addon.partnershipauthorities.model.JpressAddonPartnershipauthorities;
import io.jboot.service.JbootServiceBase;

import java.util.ArrayList;
import java.util.List;

@Bean
public class JpressAddonPartnershipauthoritiesServiceProvider extends JbootServiceBase<JpressAddonPartnershipauthorities> implements JpressAddonPartnershipauthoritiesService {

    @Override
    public Page<JpressAddonPartnershipauthorities> pagelist(Integer pageNumber,Integer pageSize) {

        if (pageNumber < 1 || pageSize < 1) {
            throw new ActiveRecordException("pageNumber and pageSize must more than 0");
        }

        List<JpressAddonPartnershipauthorities> jpressAddonPartnershipauthorities = DAO.find(
                "SELECT * from " +
                "(SELECT * from " +
                "(select ROWNUM r2,t2.* FROM " +
                "(select ROWNUM r1,t1.* from addon_partnershipauthorities t1 order by case when country_name_en='China' then 'A' end,country_name_en) t2) t3 " +
                "where rownum <="+pageSize*pageNumber+") t4 " +
                "where r2 >="+((pageNumber-1)*pageSize+1)+"");
        Record first = Db.findFirst("select count(*) totalrow from addon_partnershipauthorities");

        int totalRow = first.getInt("totalrow");

        if (totalRow == 0) {
            return new Page<JpressAddonPartnershipauthorities>(new ArrayList<JpressAddonPartnershipauthorities>(0), pageNumber, pageSize, 0, 0);	// totalRow = 0;
        }

        int totalPage = (int) (totalRow / pageSize);
        if (totalRow % pageSize != 0) {
            totalPage++;
        }

        if (pageNumber > totalPage) {
            return new Page<JpressAddonPartnershipauthorities>(new ArrayList<JpressAddonPartnershipauthorities>(0), pageNumber, pageSize, totalPage, (int)totalRow);
        }

        return new Page<JpressAddonPartnershipauthorities>(jpressAddonPartnershipauthorities, pageNumber, pageSize, totalPage, (int)totalRow);
    }
}
